package team.kirohuji.shiro.realm;

import java.util.Arrays;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import team.kirohuji.domain.user.User;
import team.kirohuji.service.user.UserService;
import team.kirohuji.shiro.token.JWTToken;
import team.kirohuji.utils.JWTUtil;

public class TokenRealm extends AuthorizingRealm {

	@Resource
	public UserService userService;

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JWTToken;
	}

	/**
	 * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = JWTUtil.getUsername(principals.toString());
		User user = userService.queryByLoginName(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		user.getRoles().forEach(r->{
			info.addRole(r.getRoleName());
		});
		return info;
	}

	/**
	 * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
		String token = (String) auth.getCredentials();
		// 解密获得username，用于和数据库进行对比
		String username = JWTUtil.getUsername(token);
		if (username == null) {
			throw new AuthenticationException("token invalid");
		}
		// 查询用户信息
		User user = userService.queryByLoginName(username);
		System.out.println("认证Token");
		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号不存在");
		}

		// 账号锁定
		if (user.getAccountStatus() == 2) {
			throw new LockedAccountException("账号已被暂停使用");
		}
		System.out.println(user.getPassword());
		if (!JWTUtil.verify(token, username, user.getPassword())) {
			throw new AuthenticationException("Username or password error");
		}
		 System.out.println(user.getPassword()); 
/*		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(),
				ByteSource.Util.bytes(user.getSalt()), getName());*/
		return  new SimpleAuthenticationInfo(token, token, "tokenReaml");
	}
}
